import styles from './index.less';
import * as React from 'react';
import { Button, Col, Divider, Dropdown, Form, Input, Menu, message, Modal, Row } from 'antd';
import { history } from 'umi';
import { IdcardOutlined, TeamOutlined, UserOutlined } from '@ant-design/icons';
import portrait from '@/images/portrait.png';
import request from '@/http';

const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 16 },
};

interface UserType {
  code: string,
  message: string,
}

interface UserInfo {
  token: string,
  loginName: string,
  userName: string,
  realName: string,
  workNumber: string,
  userType: UserType,
  adminUserId: string,
  mail: string,
  phone: string,
  sex: string,
}

interface Props {
  onUserInfoReady?: (user: UserInfo) => void,
}

export default (props: Props) => {
  const [formObjectForEdit] = Form.useForm();
  const [isModalVisible, setIsModalVisible] = React.useState(false);
  const [isModalVisibleForPassword, setIsModalVisibleForPassword] = React.useState(false);
  const [userInfo, setUserInfo] = React.useState({
    // token: '',
    // loginName: '',
    // userName: '',
    // realName: '',
    // workNumber: '',
    // userType: {
    //   code: '',
    //   message: '',
    // },
    // adminUserId: '',
    // mail: '',
    // phone: '',
    // sex: '',
    adminUserId: '',
    description: "",
    loginName: "",
    mail: "",
    phone: "",
    realName: '',
    sex: "",
    token: "",
    userId: '',
    userName: "",
    userType: '',
    workNumber: '',
  });
  const loadUserInfo = async () => {
    try {
      const result: any = await request.get('/user/getLoginUser');
      console.log(result,'1323')
      setUserInfo(result.data);
      if (props.onUserInfoReady) {
        props.onUserInfoReady(result.data);
      }
    } catch (e) {
      message.error(e.message);
    }
  };

  React.useEffect(() => {
    loadUserInfo().finally();
  }, []);

  const displayUser = (userInfo: any) => {
    if (userInfo.roleType && userInfo.roleType.code === 'TEACHER') {
      return `${userInfo.userName}（${userInfo.roleType.message}）`;
    } else if (userInfo.roleType && userInfo.roleType === 'STUDENT') {
      return `${userInfo.userName}（${userInfo.roleType.message}）`;
    }
    return `${userInfo.userName}(管理员)`;
  };

  //修改密码
  const modelOnOk = async () => {
    const data = await formObjectForEdit.validateFields();
    try {
      const result: any = await request.post('/admin/adminUser/doChangePassword', {
        ...data,
        id: userInfo.adminUserId,
      });
      if (result.success) {
        message.success('数据修改成功');
      }
    } catch (e) {
      message.error(e.message);
    }
  };
  //退出登录
  const doLogout = async () => {
    try {
      const result: any = await request.post('/user/loginout',{
        
      });
      console.log(result)
      if (result.code === '200') {
        message.success('注销成功');
        history.push('/');
      }
    } catch (e) {
      message.error(e.message);
    }
  };

  return (
    <>
      <div className={styles.mainAuth}>
        <Dropdown
          overlay={
            <div className={styles.mainAuthAction}>
              <Menu>
                <Menu.Item key="1" icon={<UserOutlined/>}>
                  <Button
                    type="link"
                    onClick={() => setIsModalVisible(!isModalVisible)}
                  >
                    个人信息
                  </Button>
                </Menu.Item>
                <Menu.Item key="2" icon={<IdcardOutlined/>}>
                  <Button
                    type="link"
                    onClick={() => setIsModalVisibleForPassword(true)}
                  >
                    密码修改
                  </Button>
                </Menu.Item>
                <Menu.Item key="3" icon={<TeamOutlined/>}>
                  <Button
                    type="link"
                    onClick={doLogout}
                  >
                    注销登录
                  </Button>
                </Menu.Item>
              </Menu>
            </div>
          }
        >
          <a>
            <img alt={userInfo.userName} src={portrait}/>
            <span>{displayUser(userInfo)}</span>
          </a>
        </Dropdown>
      </div>
      <Modal
        width={400}
        title={'个人信息'}
        visible={isModalVisible}
        maskClosable={true}
        destroyOnClose
        okText="确认"
        cancelText="取消"
        onCancel={() => {
          setIsModalVisible(false);
        }}
        onOk={() => {
          setIsModalVisible(false);
        }}
        bodyStyle={{ padding: '2px' }}
        cancelButtonProps={{ style: { display: 'none' } }}
      >
        <Row gutter={0}>
          <Col span={6} className={styles.formLabel}><span>登录名:</span></Col>
          <Col span={18} className={styles.formControl}>{userInfo.loginName}</Col>
        </Row>
        <Row gutter={0}>
          <Col span={24}><Divider style={{ margin: '2px' }}/></Col>
        </Row>
        <Row gutter={0}>
          <Col span={6} className={styles.formLabel}><span>手机号:</span></Col>
          <Col span={18} className={styles.formControl}>{userInfo.phone}</Col>
        </Row>
        <Row gutter={0}>
          <Col span={24}><Divider style={{ margin: '2px' }}/></Col>
        </Row>
        <Row gutter={0}>
          <Col span={6} className={styles.formLabel}><span>邮箱:</span></Col>
          <Col span={18} className={styles.formControl}>{userInfo.mail}</Col>
        </Row>
        <Row gutter={0}>
          <Col span={24}><Divider style={{ margin: '2px' }}/></Col>
        </Row>
        <Row gutter={0}>
          <Col span={6} className={styles.formLabel}><span>性别:</span></Col>
          <Col span={18} className={styles.formControl}>{userInfo.sex}</Col>
        </Row>
        <Row gutter={0}>
          <Col span={24}><Divider style={{ margin: '2px' }}/></Col>
        </Row>
        {/* {userInfo.userType && userInfo.userType.code === 1 ? <>
          <Row gutter={0}>
            <Col span={6} className={styles.formLabel}><span>姓名:</span></Col>
            <Col span={18} className={styles.formControl}>{userInfo.realName}</Col>
          </Row>
          <Row gutter={0}>
            <Col span={24}><Divider style={{ margin: '2px' }}/></Col>
          </Row>
          <Row gutter={0}>
            <Col span={6} className={styles.formLabel}><span>工号:</span></Col>
            <Col span={18} className={styles.formControl}>{userInfo.workNumber}</Col>
          </Row>
          <Row gutter={0}>
            <Col span={24}><Divider style={{ margin: '2px' }}/></Col>
          </Row>
          <Row gutter={0}>
            <Col span={6} className={styles.formLabel}><span>账户类型:</span></Col>
            <Col span={18} className={styles.formControl}><span>老师</span></Col>
          </Row>
        </> : <></>
        }
        {userInfo.userType && userInfo.userType.code === 'STUDENT' ? <>
          <Row gutter={0}>
            <Col span={6} className={styles.formLabel}><span>姓名:</span></Col>
            <Col span={18} className={styles.formControl}>{userInfo.realName}</Col>
          </Row>
          <Row gutter={0}>
            <Col span={24}><Divider style={{ margin: '2px' }}/></Col>
          </Row>
          <Row gutter={0}>
            <Col span={6} className={styles.formLabel}><span>学号:</span></Col>
            <Col span={18} className={styles.formControl}>{userInfo.workNumber}</Col>
          </Row>
          <Row gutter={0}>
            <Col span={24}><Divider style={{ margin: '2px' }}/></Col>
          </Row>
          <Row gutter={0}>
            <Col span={6} className={styles.formLabel}><span>账户类型:</span></Col>
            <Col span={18} className={styles.formControl}><span>学生</span></Col>
          </Row>
        </> : <></>
        }
        {userInfo.userType && userInfo.userType.code !== 'STUDENT' && userInfo.userType.code !== 'TEACHER' ? <>
          <Row gutter={0}>
            <Col span={6} className={styles.formLabel}><span>账号名:</span></Col>
            <Col span={18} className={styles.formControl}>{userInfo.userName}</Col>
          </Row>
        </> : <></>
        } */}
      </Modal>
      {/* 弹框 */}
      <Modal
        width={600}
        title={'修改密码'}
        visible={isModalVisibleForPassword}
        onCancel={() => setIsModalVisibleForPassword(false)}
        onOk={modelOnOk}
        maskClosable={false}
        destroyOnClose
        okText="确认"
        cancelText="取消"
      >
        <Form
          {...layout}
          name="editForm"
          form={formObjectForEdit}
          preserve={false}
        >
          <Form.Item
            label={'原密码'}
            name="oldPassword"
            rules={[
              { required: true, whitespace: true, message: '原密码不能为空!' },
              { max: 30, message: '最大长度不能超过30!' },
            ]}
            style={{ marginBottom: 24 }}
          >
            <Input.Password prefix={<IdcardOutlined/>} placeholder="密码"/>
          </Form.Item>
          <Form.Item
            label={'密码'}
            name="password"
            rules={[
              { required: true, whitespace: true, message: '密码不能为空!' },
              { max: 30, message: '最大长度不能超过30!' },
            ]}
            style={{ marginBottom: 24 }}
          >
            <Input.Password prefix={<IdcardOutlined/>} placeholder="密码"/>
          </Form.Item>
          <Form.Item
            name="confirmPassword"
            label="确认密码"
            dependencies={['password']}
            rules={[
              {
                required: true,
                message: '确认密码不能为空!',
              },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('password') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次密码不匹配!'));
                },
              }),
            ]}
          >
            <Input.Password/>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
}
